import {
  createRouter,
  createWebHashHistory,
  RouteMeta,
  RouteRecordRaw
} from 'vue-router'
// import Home from '../views/Home.vue'
import { getToken } from 'utils/token'

const routes: Array<RouteRecordRaw> = []

let pageList = process.env.VUE_APP_PAGE_LIST || []
try {
  pageList = JSON.parse(pageList)
} catch (error) {
  new Error(`VUE_APP_PAGE_LIST is not JSON string`)
}

pageList.forEach((page: { relativePath: string }) => {
  const { relativePath } = page
  let config
  try {
    config = require(`../views/${relativePath}/page.config.js`).default
  } catch (err) {
    config = {}
    // console.log(`../views/${relativePath}/page.config.js not found`);
  }
  const meta: RouteMeta = config.meta || {}
  const name = relativePath
    .split('/')
    .map(p => p.slice(0, 1).toLocaleUpperCase() + p.slice(1))
    .join('')
  const currentRoute = {
    meta,
    name,
    path: `/${relativePath}`,
    component: () => import(`../views/${relativePath}/entry.vue`)
  }
  routes.push(currentRoute)
})

// 添加基础basePath
// routes.forEach(route => {
//   route.path = `${basePath}${route.path}`;
// });
routes.push({
  path: '/',
  redirect: `/home`
})

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const effecToken = getToken()
  // console.log(effecToken, to.fullPath);
  const whiteDatavList = ['/', '/login']
  if (whiteDatavList.indexOf(to.path) >= 0) {
    next()
    return
  }
  if (!effecToken) {
    next({
      path: '/login',
      query: {
        redirect: to.fullPath
      }
    })
  } else {
    next()
  }
})

export default router
